package com.cscec5b.inspection.controller;

import com.cscec5b.inspection.entity.RmcRecord;
import com.cscec5b.inspection.service.PdfRenderService;
import com.cscec5b.inspection.service.RmcRecordAppService;
//import lombok.RequiredArgsConstructor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/rmc")
//@RequiredArgsConstructor
public class RmcRecordController {

    private final RmcRecordAppService app;
    private final PdfRenderService pdfRenderService;   // ★ 新增

    public RmcRecordController(RmcRecordAppService app, PdfRenderService pdfRenderService) {
        this.app = app;
        this.pdfRenderService = pdfRenderService;
    }

    @PostMapping("/save")
    public Map<String,Object> save(@RequestBody RmcRecord body){
        return app.save(body);
    }

    @GetMapping("/{id}")
    public Map<String,Object> detail(@PathVariable long id){
        return app.detail(id);
    }

    @GetMapping("/project/{projectId}")
    public List<RmcRecord> list(@PathVariable long projectId){
        return app.listByProject(projectId);
    }

    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> export(@PathVariable long id,
                                         @RequestParam(required = false) String projectName) {
        // 1) 拿到 data（可能是实体，也可能是 Map），统一转为实体
        Map<String, Object> res = app.detail(id);
        Object dataObj = res != null ? res.get("data") : null;
        if (dataObj == null) return ResponseEntity.notFound().build();

        RmcRecord rec;
        if (dataObj instanceof RmcRecord) {
            rec = (RmcRecord) dataObj;
        } else {
            rec = new ObjectMapper().convertValue(dataObj, RmcRecord.class);
        }

        // 2) 组装模板数据（模板占位符：见 rmc_record.html）
        Map<String, Object> data = new HashMap<>();
        data.put("projectName", projectName != null ? projectName : "");
        data.put("projectId", rec.getProjectId());
        data.put("weather", rec.getWeather());
        data.put("temperature", rec.getTemperature());
        data.put("pageNo", rec.getPageNo());
        data.put("supplyUnit", rec.getSupplyUnit());
        data.put("designStrength", rec.getDesignStrength());
        data.put("mixPlant", rec.getMixPlant());
        data.put("contactPhone", rec.getContactPhone());

        data.put("pStart", fmt(rec.getPouringDateS()));   // ← 对应 getPouringDateS()
        data.put("pEnd",   fmt(rec.getPouringDateE()));   // ← 对应 getPouringDateE()

        data.put("slump", rec.getSlump());
        data.put("continuousTime", rec.getContinuousTime());
        data.put("initialSetting", rec.getInitialSetting());
        data.put("cubeStrength", rec.getCubeStrength());

        List<String> truckNos = rec.getTruckNos() == null ? Collections.emptyList() : rec.getTruckNos();
        data.put("truckNos", String.join("、", truckNos));

        data.put("samplingTimes", rec.getSamplingTimes());
        data.put("samplingValues", joinNums(rec.getSamplingValues()));

        data.put("cubeCurr", rec.getCubeGroupsCurr());
        data.put("cubeMid", rec.getCubeGroupsMid());
        data.put("cubeSpl", rec.getCubeGroupsSpl());
        data.put("rebarValue", rec.getRebarValue());

        data.put("inspectorOpinion", rec.getInspectorOpin()); // ← 对应 getInspectorOpin()
        data.put("recorder", rec.getRecorder());
        data.put("isTrueLabel", Boolean.TRUE.equals(rec.getTrue()) ? "是" : "否"); // ← 对应 getTrue()
        data.put("dateStr", LocalDate.now().toString());

        List<Map<String, Object>> checklist =
                rec.getChecklist() == null ? Collections.emptyList() : rec.getChecklist();
        data.put("checklistData", checklist);

        // 3) 渲染 PDF（有中文字体用 renderWithFont，否则用 render）
        byte[] bytes = pdfRenderService.renderWithFont(
                "templates/rmc_record.html",
                data,
                "fonts/simhei.ttf",    // 你放在 resources/fonts 下的字体文件
                "custom"                            // 模板里 CSS 使用的 font-family
        );

        String fileName = URLEncoder.encode("预拌混凝土施工记录_" + id + ".pdf", StandardCharsets.UTF_8);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + fileName)
                .contentType(MediaType.APPLICATION_PDF)
                .body(bytes);
    }

    /** LocalDateTime -> "yyyy-MM-dd HH:mm:ss" 简单格式（缺省直接把 T 换空格） */
    private static String fmt(LocalDateTime dt) {
        return dt == null ? "" : dt.toString().replace('T', ' ');
    }

    /** 数字列表用顿号拼接：1、2、3 */
    private static String joinNums(List<? extends Number> list) {
        if (list == null || list.isEmpty()) return "";
        return list.stream()
                .map(n -> n == null ? "" : String.valueOf(n))
                .collect(Collectors.joining("、"));
    }


}
